package com.myz.rabbitmq.transaction;

import com.myz.rabbitmq.utils.ConnectionUtils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;

/**
 * 事务机制
 *
 * @author maoyz on 18-4-11.
 */
public class TxSend {
    private static final Logger logger = LoggerFactory.getLogger(TxSend.class);
    /**
     * 队列名称
     */
    private final static String QUEUE_NAME = "tx_work_queue";

    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtils.getConnection();

        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        String message = "Hello RabbitMQ";
        try {
            // 将当前channel设置成transaction模式
            channel.txSelect();
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes(StandardCharsets.UTF_8));
            // 异常信息
            // int i = 1 / 0;
            // 提交事务
            channel.txCommit();
        } catch (Exception e) {
            logger.error("回滚事务...", e);
            // 回滚事务
            channel.txRollback();
        } finally {
            channel.close();
            connection.close();
        }
    }
}
